package cn.wolfcode.ssm.controller;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.User;
import cn.wolfcode.ssm.query.QueryObject;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.util.JSONResult;
import cn.wolfcode.ssm.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("employees")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @GetMapping("list")
    public Object list(QueryObject qo){
        return employeeService.query(qo);
    }

    @PostMapping("saveOrUpdate")
    public Object save(Employee employee){
        JSONResult result = new JSONResult();


        if (!SecurityUtils.getSubject().hasRole("admin")) {
            result.mark("您没有权限");
            return result;
        }

        try {
            employeeService.save(employee);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }

        return result;
    }

    @PutMapping("saveOrUpdate")
    public Object update(Employee employee){
        JSONResult result = new JSONResult();

        try {
            employeeService.update(employee);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }

        return result;
    }

    @DeleteMapping("delete")
    public Object delete(Long empId){
        JSONResult result = new JSONResult();

        try {
            employeeService.delete(empId);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }

        return result;
    }

}
